package com.chixing.jdbc.day01.dao.impl;

import com.chixing.jdbc.day01.config.DBConnUtil;
import com.chixing.jdbc.day01.dao.DepartmentDao;
import com.chixing.jdbc.day01.pojo.Department;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class DepartmentDaoImpl implements DepartmentDao {
    @Override
    public int insert(Department department) {
        int rows = 0;
        Connection connection = DBConnUtil.getConnection();
        PreparedStatement pstmt = null;
        String sql="insert into dept values(?,?,?)";
        try {
            pstmt =connection.prepareStatement(sql);
            pstmt.setInt(1,department.getDepartmentNo());
            pstmt.setString(2,department.getDepartentName());
            pstmt.setString(3,department.getDepartmentLocation());
            rows = pstmt.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            if(pstmt !=null) {
                try {
                    pstmt.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if(connection !=null) {
                try {
                    connection.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
        return rows;
    }

    @Override
    public int delete(int departmentNo) {
        int rows = 0;
        Connection connection = DBConnUtil.getConnection();
        String sql ="delete from dept where deptno = ?";
        PreparedStatement pstmt = null;
        try {
            pstmt =  connection.prepareStatement(sql);
            pstmt.setInt(1,departmentNo);
            rows = pstmt.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            if(pstmt !=null) {
                try {
                    pstmt.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            DBConnUtil.closeConnection();
        }
        return rows;
    }

    @Override
    public int update(Department department) {
        return 0;
    }

    @Override
    public Department selectByPrimaykey(int departmentNo) {
        return null;
    }
}
